<template>
  <!-- <div>虚拟信用卡管理</div> -->
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <VBatchInput
          v-model="form.channel"
          placeholder="信用卡渠道"
          @search="refresh"
          class="w-60"
        />
        <VBatchInput
          v-model="form.cardNumber"
          placeholder="信用卡号"
          @search="refresh"
          class="w-60"
        />
        <VSelects
          v-model="form.state"
          placeholder="状态"
          class="w-50"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :dataSourse="optionsData?.virtual_credit_card_state || []"
        />
        <VGroup>
          <VSelects
            v-model="form.user.type"
            :dataSourse="othersData.virtual_attribution"
            class="w-[100px]"
          />
          <VCascader
            v-model="form.user.value"
            collapse-tags
            style="width: 200px"
          />
        </VGroup>
        <div class="w-[350px]">
          <el-date-picker
            v-model="form.createdAt"
            type="datetimerange"
            start-placeholder="添加日期开始时间"
            end-placeholder="添加日期结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-bind="$attrs"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 2, 1, 23, 59, 59),
            ]"
            class="w-full"
          />
        </div>
        <div class="w-[320px]">
          <el-date-picker
            v-model="form.expiryDate"
            type="daterange"
            start-placeholder="到期日期开始时间"
            end-placeholder="到期日期结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="w-full"
          />
        </div>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions">
          <template #left>
            <span>说明:系统自动在信用卡过期前3天,发飞书消息通知对应负责人</span>
          </template>
        </VActionBar>
      </template>
      <template #operation="{ row }">
        <el-button
          type="primary"
          link
          @click="handleAdd(row)"
          v-hasPermi="[financialManageAuthList.virtual_card_manage.edit]"
        >
          编辑
        </el-button>
        <el-button
          type="danger"
          link
          @click="handleDelete(row.id)"
          v-if="row?.state?.value !== 1"
          v-hasPermi="[financialManageAuthList.virtual_card_manage.delete]"
        >
          删除
        </el-button>
        <el-button type="primary" link @click="handleLog(row.id)">
          日志
        </el-button>
      </template>
    </VTable>
    <Add
      v-model="addVisible"
      :title="addTitle"
      :data="addData"
      @refresh="refresh"
      @close="addData = null"
    />
    <UpdateState
      v-model="stateVisible"
      :title="stateTitle"
      :data="stateData"
      :optionsData="optionsData"
      @refresh="refresh"
      @close="stateData = null"
    />
    <VLog
      v-model="logVisible"
      :autoLoad="false"
      :module="8"
      :id="logId"
      @close="logId = ''"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import othersData from "@/data/search.js";
import { getVirtualCreditCard, deleteVirtualCreditCard } from "./api.js";
import tagStatus from "@/components/tagStatus/index.vue";
import { transformData } from "@/utils/tools.js";
import Add from "./components/add/index";
import UpdateState from "./components/updateState/index";
import { useEnumSelect } from "@/hooks/index.js";
import { financialManageAuthList } from "@/Auth/financial-manage.js";
import { formatTime } from "@/utils/time.js";
const { proxy } = getCurrentInstance();
const { options: optionsData } = useEnumSelect({
  params: ["virtual_credit_card_state"],
});
const tableRef = ref();
// 查询
const refresh = () => {
  tableRef?.value.query();
};

//新增
const addVisible = ref(false);
const addData = ref(null);
const addTitle = ref("新增");
const handleAdd = (row) => {
  addVisible.value = true;
  let data = null;
  if (row?.id) {
    const { state, attribution } = row || {};
    data = {
      ...row,
      state: state?.value,
      attribution: Number(attribution),
    };
  }
  addData.value = data || null;
  addTitle.value = data?.id ? "编辑" : "新增";
};

//状态修改
const stateVisible = ref(false);
const stateTitle = ref("");
const stateData = ref({});
const handleState = (title, type) => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const now = formatTime();
  const validRecords = [];
  const invalidRecords = [];
  for (const item of records) {
    const state = item.state?.value;
    const expiryStr = item.expiryDate ? formatTime(item.expiryDate) : null;

    const isValid =
      state === 1 || ([2, 3].includes(state) && expiryStr && expiryStr > now);

    if (isValid) {
      validRecords.push(item);
    } else {
      invalidRecords.push(item);
    }
  }
  const ids = validRecords.map((item) => item.id);
  const invalidLength = invalidRecords.length;

  let msg = "-";
  if (invalidLength) {
    msg =
      invalidRecords.map((item) => item.cardNumber).join("，") +
      "信用卡号[ '过期' ]或[ '作废' ]的[ '到期日期' ]小于[ '当前日期' ],系统将自动跳过不修改";
  }
  stateData.value = {
    ids,
    type,
    validLength: validRecords.length,
    invalidLength,
    msg,
  };
  stateTitle.value = title;
  stateVisible.value = true;
};

//删除
const handleDelete = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除
        <span class="text-[#3366F1] px-[4px]">{1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await deleteVirtualCreditCard({ id });
          if (code !== 200) return ElMessage.success(message);
          ElMessage.success("删除成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

//日志
const logVisible = ref(false);
const logId = ref("");
const handleLog = (item) => {
  logId.value = item;
  logVisible.value = true;
};
const tableOptins = reactive({
  formConfig: {
    data: {
      time: {
        type: "expiryDate",
        value: null,
      },
      user: {
        type: "attribution",
        value: "",
      },
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      title: "ID",
      field: "id",
      width: 180,
    },
    {
      title: "信用卡渠道",
      field: "channel",
      width: 180,
    },
    {
      title: "信用卡号",
      field: "cardNumber",
      width: 180,
    },
    {
      title: "到期日期",
      field: "expiryDate",
      width: 180,
    },
    {
      title: "状态",
      slots: {
        default: ({ row }) => {
          return (
            <tagStatus
              code={row?.state}
              type={[
                { label: 3, value: "info" },
                { label: 1, value: "primary" },
                { label: 2, value: "danger" },
              ]}
            />
          );
        },
      },
      width: 90,
    },
    {
      title: "负责人",
      field: "attributionUser",
      width: 180,
    },
    {
      title: "备注信息",
      field: "remark",
      minWidth: 180,
    },
    {
      title: "添加人",
      field: "createUser",
      width: 180,
    },
    {
      title: "添加时间",
      field: "createdAt",
      width: 180,
    },
    {
      title: "操作",
      width: 160,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        const { state } = form;
        let params = transformData(form);
        params.state = state?.join(",");
        return getVirtualCreditCard({ ...params, ...page });
      },
    },
  },
});
const actions = [
  {
    label: "新增",
    type: "primary",
    icon: "add1",
    fn: handleAdd,
    permission: [financialManageAuthList.virtual_card_manage.add],
  },
  {
    label: "批量修改信用卡状态",
    type: "primary",
    fn: () => handleState("批量修改信用卡状态", 1),
    permission: [financialManageAuthList.virtual_card_manage.state],
  },
  {
    label: "批量修改负责人",
    type: "primary",
    fn: () => handleState("批量修改负责人", 2),
    permission: [financialManageAuthList.virtual_card_manage.attribution],
  },
];
</script>
<style lang="scss" scoped></style>
